<!--
 * @Description: 周计划列表
 * @Author: wind-lc
 * @version: 1.0
 * @Date: 2023-03-14 14:15:47
 * @LastEditTime: 2023-03-31 15:52:59
 * @FilePath: \cscec-pms-admin\src\views\construction\weekPlan\index.vue
-->
<template>
  <base-breadcrumb>
    <!-- 搜索 -->
    <searchData
      :search-data="searchOption"
      :custom-reset="customReset"
      @search="search"
      @loadWeek="loadWeek"
    />
    <!-- 搜索 -->
    <a-card>
      <a-button
        v-btnPermission="'pm_066_exp_05'"
        type="primary"
        class="export-btn"
        :loading="exporting"
        @click="exportList"
        style="margin-bottom: 10px;"
      >导出全部</a-button>
      <div class="pub-table-select-count">
        <a-icon
          type="info-circle"
          theme="twoTone"
        />
        <span style="margin-right: 12px">
          总共：<span class="totalNum">{{ total }}</span>
        </span>
      </div>
      <s-table
        ref="table"
        row-key="id"
        :columns="columns"
        :data="loadData"
        show-size-changer
        show-quick-jumper
        :scroll="{ x: 2020, y: 440 }"
        :show-pagination="false"
        :children-column-name="'childTree'"
        :expanded-row-keys="expandedRowKeys"
        @expand="expandedRowsChange"
      >
        <template
          slot="status"
          slot-scope="text,record"
        >
          <a-badge
            v-if="record.tageCode === 'PD'"
            :status="text | statusTypeFilter"
            :text="text | statusFilter"
          />
        </template>
        <template
          slot="operation"
          slot-scope="text, record"
        >
          <MoreButton>
            <a
              v-if="record.tageCode == 'PD'"
              v-btnPermission="'pm_066_loo_01'"
              @click="handleDetail(record)"
            >查看</a>
            <!-- && record.thisWeek -->
            <a
              v-if="record.tageCode == 'PD' && (record.status== '0' || record.status=='3') && record.thisWeek"
              v-btnPermission="'pm_066_edi_02'"
              @click="handleUpdate(record)"
            >编辑</a>
            <a
            v-if="record.tageCode == 'PD' && ( record.status== '2' || record.status=='4')"
              v-btnPermission="'pm_066_imp_03'"
              @click="handleImplementationManagement(record)"
            >实施管理</a>
            <a
              v-if="record.tageCode == 'PD' && record.status!='0'"
              @click="$bus.$emit('showApprovalDetailsDialog', record.weekId)"
            >审批信息</a>
            <a
              v-if="record.tageCode == 'PD'"
              v-btnPermission="'pm_066_exp_06'"
              @click="handleExport(record)"
            >导出</a>
          </MoreButton>
        </template>
      </s-table>
    </a-card>
    <!-- 导出 -->
    <PlanExport
      :visible.sync="visible"
      :typeList="['excel']"
      :downloadFun="downloadFun"
    />
  </base-breadcrumb>
  
</template>
<script>
import { searchOption, columns, statusMap } from './model.js'
import weekPlanApi from '@/api/construction/weekPlanApi'
import PlanExport from '@/views/construction/components/PlanExport'
export default {
  name: 'weekPlan' + Date.now(),
  components: {
    PlanExport
  },
  filters: {
    // 状态过滤
    statusFilter(type) {
      const key = type.toString()
      return statusMap[key] && statusMap[key].text
    },
    statusTypeFilter(type) {
      const key = type.toString()
      return statusMap[key] && statusMap[key].status
    }
  },
  data() {
    return {
      // 查询参数
      searchData: {},
      // 搜索选项
      searchOption,
      // 表头
      columns,
      // 统计
      total: 0,
      // 默认展开项
      expandedRowKeys: [],
      // 所属周默认值
      belongWeek: '',
       // 导出中
      exporting: false,
      visible: false,
      // 导出时传入接口
      downloadFun: {},
    }
  },
  created() {
    this.getWbsTemplateList()
  },
  methods: {
    /**
     * @description: 获取项目业态
     * @param {void}
     * @return {void}
     */
    getWbsTemplateList() {
      weekPlanApi.wbstemplate({ pageNo: 1, pageSize: 2000 }).then((res) => {
        this.searchOption[1].data = res.data.map((item) => {
          return {
            label: item.formatName,
            value: item.formatId
          }
        })
      })
    },
    /**
     * @description: 获取所属周列表
     * @return {void}
     */
    getWeekList() {
      weekPlanApi.belongWeekSelect({ pageNo: 1, pageSize })
    },
    /**
     * @description: 表格数据加载方法
     * @param {Object} parameter 分页信息
     * @return {Promise} 接口Promise
     */
    async loadData(parameter) {
      try {
        if ((this.searchData?.belongWeek ?? '') === '') {
          return Promise.resolve({
            data: []
          })
        }
        const {
          data: { treeVO, total, expandedRowKeys }
        } = await weekPlanApi.queryScheduleNodeWeekTree({
          ...this.searchData,
          orgId: this.$userInfo()?.currentPost?.id
        })
        this.total = total
        this.expandedRowKeys = expandedRowKeys || []
        return Promise.resolve({
          data: treeVO ? [treeVO] : []
        })
      } catch (error) {
        console.log(error)
        return Promise.reject(error)
      }
    },
    /**
     * @description: 搜索
     * @param {Object} value 搜索数据
     * @return {Void}
     */
    search(value) {
      this.searchData = value || {}
      if ((this.searchData?.belongWeek ?? '') === '') {
        this.$message.warning('缺少所属周')
      }
      this.$refs.table.refresh(true)
    },
    /**
     * @description: 所属周首次加载完成且有默认值回调
     * @param {string} val 默认值
     * @return {void}
     */
    loadWeek(val) {
      this.searchData = {
        ...this.searchData,
        belongWeek: val
      }
      this.belongWeek = val
      this.$refs.table.refresh(true)
    },
    /**
     * @description: 手动展开
     * @param {boolean} expanded 是否展开
     * @param {object} record 行
     * @return {void}
     */
    expandedRowsChange(expanded, record) {
      if (expanded) {
        this.expandedRowKeys.push(record.id)
      } else {
        this.expandedRowKeys.splice(
          this.expandedRowKeys.findIndex((el) => el === record.id),
          1
        )
      }
    },
    /**
     * @description: 查看
     * @param {object} record 行数据
     * @return {void}
     */
    handleDetail({ id: projectId, status, weekId: planId }) {
      this.$router.push({
        path: '/construction/weekPlan/weekPlanView',
        query: {
          projectId,
          planId,
          pageType: 'detail',
          status
        }
      })
    },
    /**
     * @description: 编辑
     * @param {object} record 行数据
     * @return {void}
     */
    handleUpdate({ id: projectId, status, weekId: planId }) {
      this.$router.push({
        path: '/construction/weekPlan/weekPlanView',
        query: {
          projectId,
          pageType: 'update',
          planId,
          status
        }
      })
    },
    /**
     * @description: 实施管理
     * @param {object} record 行数据
     * @return {void}
     */
    handleImplementationManagement({ id: projectId, status, weekId: planId, thisWeek }) {
      this.$router.push({
        path: '/construction/weekPlan/implementationManagementWeekPlan',
        query: {
          projectId,
          status,
          planId,
          thisWeek
        }
      })
    },
    /**
     * @description: 自定义重置
     * @param {object} form 表单对象
     * @return {void}
     */    
    customReset(form){
      form.setFieldsValue({'belongWeek': this.belongWeek})
    },
        /**
     * @description: 导出全部
     * @return {void}
     */
     async exportList() {
      try {
        this.exporting = true
        this.handleDownload(await weekPlanApi.scheduleNodeWeekExclWeek({
          ...this.searchData,
          orgId: this.$userInfo()?.currentPost?.id
        }))
      } catch (error) {
        console.log(error)
      } finally {
        this.exporting = false
      }
    },
    /**
     * @description: 下载
     * @return {void}
     */
    handleDownload(res) {
      console.log(res,2222)
      const blob = new Blob([res.data])
      const filename = decodeURIComponent(res.headers['content-disposition'].split('filename=')[1])
      const downloadElement = document.createElement('a')
      const href = window.URL.createObjectURL(blob) // 创建下载的链接
      downloadElement.href = href
      downloadElement.download = filename // 获取文件名
      document.body.appendChild(downloadElement)
      downloadElement.click() //点击下载
      document.body.removeChild(downloadElement) //下载完成移除元素
      window.URL.revokeObjectURL(href) //释放blob对象
    },
        /**
     * @description: 导出
     * @param {object} record 行
     * @return {void}
     */
     handleExport(record) {
      this.visible = true
      // 导出接口
      this.downloadFun = {
        project: () => {
          return weekPlanApi.schedulePlanWeekExcl(record?.rootId)
        },
        excel: () => {
          return weekPlanApi.schedulePlanWeekExcl(record?.rootId)
        }
      }
    }
  }
}
</script>
<style lang="less" scoped>
</style>
